﻿using anydata.Entitys; 

namespace anydata.Extensions
{
    public static class EntityBaseExtensions
    {
        public static double GetDoubleValue(this EntityBase? thing, FormField field)
        {
            if (thing is null)
            {
                return 0;
            }
            var fieldValue = thing[field.code];
            if (fieldValue is not null)
            {
                if (double.TryParse(fieldValue.ToString(), out var value))
                {
                    return value;
                }
            }
            return 0;
        }

        public static int GetIntValue(this EntityBase? thing, FormField field)
        {
            if (thing is null)
            {
                return 0;
            }
            var fieldValue = thing[field.code];
            if (fieldValue is not null)
            {
                if (double.TryParse(fieldValue.ToString(), out var value))
                {
                    return (int)Math.Round(value);
                }
            }
            return 0;
        }

        public static string GetStringValue(this EntityBase? thing, FormField field)
        {
            if (thing is null)
            {
                return null;
            }
            return thing[field.code]?.ToString()  ?? null;
        }
        public static DateTime? GetDateValue(this EntityBase? thing, FormField field)
        {
            if (thing is null)
            {
                return null;
            }
            var fieldValue = thing[field.code];
            if (fieldValue is not null)
            {
                if (DateTime.TryParse(fieldValue.ToString(), out var value))
                {
                    return value.ToLocalTime();
                }
            }
            return null;
        }
    }
}
